<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/all.conf.php');
require_once(__PHY_WEB.__DIR_ADM.'/admin.inc.php');
require_once(__PHY_LIB.'/class/uAd.class.php');

$rReq = validate($_REQUEST, 'msg:u|action:e[list,edit,new,add,update,delete]');
$sMsg = $rReq['msg'];
$sAction = $rReq['action'];

if ('add' == $sAction) {
	do {
		$rP = validate($_POST, 'location:U|obj_id:N');
		if (!$rP) { $sMsg = '参数错误'; break; }
		$oAd = new uAd();
		$oAd->set('location', $rP['location']);
		$oAd->set('obj_id', $rP['obj_id']);
		$oAd->set('rank', $oAd->calcNewRank());
		if ($x = $oAd->invalid()) {
			$sMsg = '出错啦。原因：'.$x; break;
		}
		elseif ($oAd->insert()) {
			if ($_FILES['img1']['tmp_name']) {
				$oAd->saveFile($_FILES['img1']['tmp_name'], 'img1');
				$oAd->update();
			}
			$sMsg = '添加成功'; break;
		}
		else {
			$sMsg = '添加失败！！'; break;
		}
	} while (false);
	$sAction = 'list';
}
elseif ('update' == $sAction) {
	do {
		$rP = validate($_POST, 'id:N|location:U|obj_id:N|rank:N');
		if (!$rP) { $sMsg = '标题为空，或者序号错误'; break; }
		$oAd = new uAd($rP['id']);
		$oAd->set('location', $rP['location']);
		$oAd->set('obj_id', $rP['obj_id']);
		if (!$oAd->update()) { $sMsg = '更新失败！！'; break; }
		if ($_FILES['img1']['tmp_name']) {
			$oAd->saveFile($_FILES['img1']['tmp_name'], 'img1');
			$oAd->update();
		}
		if (!$oAd->rankTo($rP['rank'])) { $sMsg = '更新序号失败！！'; break; }
		$sMsg = '修改成功'; break;
	} while (false);
	$sAction = 'list';
}
elseif ('delete' == $sAction) {
	do {
		$rP = validate($_POST, 'id:N');
		if (!$rP) { $sMsg = '标题为空，或者序号错误'; break; }
		$oAd = new uAd($rP['id']);
		if (!(0 < $oAd->getID())) { $sMsg = '该记录不存在。'; break; }
		if ($oAd->delete()) { $sMsg = '删除成功'; break; }
		else { $sMsg = '删除失败！！'; break; }
	} while (false);
	$sAction = 'list';
}

if ('new' == $sAction) {
}
elseif ('edit' == $sAction) {
	$oOne = new uAd($_REQUEST['id']);
	$oTpl->assign('rOne', $oOne->getData());
	/// 序号列表 ///
	$oList = new uAdList();
	$oList->cfgWhere("location='".$oOne->get('location')."'");
	$oList->cfgOrder("rank");
	$oList->load();
	$oTpl->assign('rSlctRanks', $oList->fetchArray());
}
elseif ('list' == $sAction) {
	$oList = new uAdList();
	$oList->cfgOrder("location,rank");
	$oList->load();
	while ($oOne = $oList->nextItem()) {
	}
	$oTpl->assign('rList', $oList->fetchArray());
}

$oTpl->assign('sMsg', $sMsg);
$oTpl->assign('sAction', $sAction);
$oTpl->display(dirname(__FILE__).'/'.basename(__FILE__, '.php').'.tpl');
?>
